package com.ruoyi.zsyh.controller.applet.agent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.zsyh.controller.applet.user.WxUserController;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 产品_厂家Controller
 *
 * @author yuexl
 * @date 2021-12-08
 */
@Controller
@RequestMapping("/applet/zsyh/partsFactory")
public class ZsyhPlatformPartsFactoryAppletController extends BaseController
{
    private Logger logger = LoggerFactory.getLogger(ZsyhPlatformPartsFactoryAppletController.class);
    @Autowired
    private IZsyhPlatformPartsService zsyhPlatformPartsService;

    @Autowired
    private IZsyhPlatformPartsattributeService zsyhPlatformPartsattributeService;

    @Autowired
    private IZsyhPlatformFactoryService zsyhPlatformFactoryService;

    @Autowired
    private IZsyhAgentAddressService zsyhAgentAddressService;

    @Autowired
    private IZsyhAgentOrderService zsyhAgentOrderService;

    @Autowired
    private IZsyhAgentOrderRelService zsyhAgentOrderRelService;

    @Autowired
    private IZsyhAgentPartsService zsyhAgentPartsService;

    @Autowired
    private IZsyhAgentPartsattributeService zsyhAgentPartsattributeService;

    @Autowired
    private IZsyhFactoryBankcardsService zsyhFactoryBankcardsService;


    @Autowired
    private IZsyhPartsSalesService zsyhPartsSalesService;

    @Autowired
    private IZsyhPartsQrcodeService zsyhPartsQrcodeService;

    @Autowired
    private IZsyhPartsQrcodeHistoryService zsyhPartsQrcodeHistoryService;

    @Autowired
    private IZsyhAgentMessageService zsyhAgentMessageService;


    /**
     * 获取银行名称list
     * @return
     */
    @RequestMapping("/getFactoryBankTypeList")
    @ResponseBody
    public AjaxResult getFactoryBankTypeList(){
        List<Map> list = zsyhFactoryBankcardsService.selectZsyhFactoryBankType();
        return success("操作成功", list);
    }

    /**
     * 获取厂家银行账户列表
     * @return
     */
    @RequestMapping("/getFactoryBankCards")
    @ResponseBody
    public AjaxResult getFactoryBankCards(String factoryId){
        ZsyhFactoryBankcards bankcards = new ZsyhFactoryBankcards();
        bankcards.setFactoryId(factoryId);
        List<ZsyhFactoryBankcards> list = zsyhFactoryBankcardsService.selectZsyhFactoryBankcardsList(bankcards);
        return success("操作成功", list);
    }

    /**
     * 获取厂家银行默认账户
     * @return
     */
    @RequestMapping("/getFactoryBankCardsDefault")
    @ResponseBody
    public AjaxResult getFactoryBankCardsDefault(String factoryId){
        ZsyhFactoryBankcards bankcards = new ZsyhFactoryBankcards();
        bankcards.setFactoryId(factoryId);
        bankcards.setIsDefault("1");
        List<ZsyhFactoryBankcards> list = zsyhFactoryBankcardsService.selectZsyhFactoryBankcardsList(bankcards);
        if(list.size() > 0){
            return success("操作成功", list.get(0));
        }else{
            bankcards.setIsDefault(null);
            list = zsyhFactoryBankcardsService.selectZsyhFactoryBankcardsList(bankcards);
            if(list.size() > 0){
                return success("操作成功", list.get(0));
            }else{
               return error("暂无账户信息");
            }
        }
    }

    /**
     * 添加银行账户
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/saveFactoryBankCards")
    @ResponseBody
    public AjaxResult saveFactoryBankCards(String factoryId, String cardName, String cardNo, String bandTypeId){
        ZsyhFactoryBankcards bankcards = new ZsyhFactoryBankcards();
        bankcards.setId(IdWorker.getId());
        bankcards.setFactoryId(factoryId);
        bankcards.setCardName(cardName);
        bankcards.setCardNo(cardNo);
        bankcards.setBankTypeId(bandTypeId);
        bankcards.setIsDefault("0");
        zsyhFactoryBankcardsService.insertZsyhFactoryBankcards(bankcards);
        return success("操作成功");
    }

    /**
     * 修改银行账户
     * @return
     */
    @RequestMapping("/updateFactoryBankCards")
    @ResponseBody
    public AjaxResult updateFactoryBankCards(String id, String cardName, String cardNo, String bandTypeId){
        ZsyhFactoryBankcards bankcards = new ZsyhFactoryBankcards();
        bankcards.setId(id);
        bankcards.setCardName(cardName);
        bankcards.setCardNo(cardNo);
        bankcards.setBankTypeId(bandTypeId);
        bankcards.setIsDefault("0");
        zsyhFactoryBankcardsService.updateZsyhFactoryBankcards(bankcards);
        return success("操作成功");
    }

    /**
     * 删除厂家银行账户
     * @return
     */
    @RequestMapping("/deleteFactoryBankCards")
    @ResponseBody
    public AjaxResult deleteFactoryBankCards(String id){
        zsyhFactoryBankcardsService.deleteZsyhFactoryBankcardsById(id);
        return success("操作成功");
    }

    /**
     * 获取厂家首页累计金额
     * @return
     */
    @RequestMapping("/getMoneyAllByFactoryId")
    @ResponseBody
    @Transactional
    public AjaxResult getMoneyAllByFactoryId(String factoryId){
        return success("操作成功", zsyhAgentOrderService.getMoneyAllByFactoryId(factoryId).get("moneyAll"));

    }

    /**
     * 获取预定单列表
     * @param orderState 1待接单，2待发货，3已发货
     * @return
     */
    @RequestMapping("/getFactoryOrderList")
    @ResponseBody
    @Transactional
    public AjaxResult getFactoryOrderList(String pageNum, String pageSize, String factoryId, String orderState){
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setFactoryId(factoryId);
        Map map = new HashMap();
        map.put("orderState", orderState);
        int num = 0;
        int size = 10;
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            num = Integer.valueOf(pageNum);
            size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
        }
        map.put("beginPos", num);
        map.put("pageSize", size);
        order.setParams(map);
        List<ZsyhAgentOrder> list = zsyhAgentOrderService.selectZsyhAgentOrderListByFactoryId(order);
        return success("操作成功", list);

    }

    /**
     * 获取预定单详情
     * @param id
     * @return
     */
    @RequestMapping("/getFactoryOrderDetails")
    @ResponseBody
    @Transactional
    public AjaxResult getReserveOrderDetails(String id){
        ZsyhAgentOrder order = zsyhAgentOrderService.selectZsyhAgentOrderDetailsByFactoryId(id);
        return success("操作成功", order);
    }


    /**
     * 获取预订单 产品清单
     * @param id
     * @return
     */
    @RequestMapping("/getFactoryOrderRelList")
    @ResponseBody
    @Transactional
    public AjaxResult getFactoryOrderRelList(String id){
        ZsyhAgentOrderRel rel = new ZsyhAgentOrderRel();
        rel.setOrderId(id);
        List<ZsyhAgentOrderRel> list = zsyhAgentOrderRelService.selectZsyhAgentOrderRelList(rel);
        return success("操作成功", list);
    }


    /**
     * 获取此厂家下所有产品规格
     * @param factoryId
     * @return
     */
    @RequestMapping("/getPartsListByFactoryId")
    @ResponseBody
    public AjaxResult getPartsListByFactoryId(String factoryId){
        return AjaxResult.success("获取成功", zsyhPlatformPartsService.selectZsyhPlatformPartsByFactoryId(factoryId));
    }

    /**
     * 添加产品
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/savePartsAttributeToOrder")
    @ResponseBody
    @Transactional
    public AjaxResult submitReservation(String id, String partsJson){
        //保存订单信息
        Date date = new Date();
        double moneyAll = 0.00;

        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhAgentOrderRel> relList = new ArrayList<>();
        List<ZsyhAgentOrderRel> relListUpdate = new ArrayList<>();
        ZsyhAgentOrderRel orderRel = new ZsyhAgentOrderRel();
        orderRel.setOrderId(id);
        List<ZsyhAgentOrderRel> oldRelList = zsyhAgentOrderRelService.selectZsyhAgentOrderRelList(orderRel);
        Map<String, String> map = new HashMap<>();
        for(ZsyhAgentOrderRel a:oldRelList){
//            BigDecimal price = a.getOrderPrice();
//            String count = a.getOrderCount();
            String sellCount = a.getOrderSellCount();
            BigDecimal sellPrice = a.getOrderSellPrice();
            moneyAll += sellPrice.multiply(new BigDecimal(sellCount)).doubleValue();
            map.put(a.getAttributeId()+"num", sellCount);
            map.put(a.getAttributeId()+"id", a.getId());
        }
        for(Map<String, Object> a:list){//解析预定产品，并保存
            String attributeId = String.valueOf(a.get("attributeId"));
            String partsId = String.valueOf(a.get("partsId"));
            String count = String.valueOf(a.get("count"));
            BigDecimal price = new BigDecimal(String.valueOf(a.get("price")));
            String oldCount = map.get(attributeId+"num");
            if(EmptyUtils.isNotEmpty(oldCount)){//订单之前有此商品，数量合并
                String relId = map.get(attributeId+"id");
                ZsyhAgentOrderRel rel = ZsyhAgentOrderRel.getInstance();
                rel.setId(relId);
                double countAll = Double.valueOf(count) + Double.valueOf(oldCount);
                String count_all = "";
                if(countAll%1 == 0){
                    int i = (int) countAll;
                    count_all = String.valueOf(i);
                }else{
                    count_all = String.valueOf(countAll);
                }
//                rel.setOrderCount(count_all);
                rel.setOrderSellCount(count_all);

                relListUpdate.add(rel);
            }else{
                ZsyhAgentOrderRel rel = ZsyhAgentOrderRel.getInstance();
                rel.setId(IdWorker.getId());
                rel.setOrderId(id);
                rel.setPartsId(partsId);
                rel.setAttributeId(attributeId);
                rel.setOrderCount("0");
                rel.setOrderSellCount(count);
                rel.setOrderPrice(price);
                rel.setOrderSellPrice(price);
                rel.setCreateTime(date);

                relList.add(rel);
            }

            moneyAll += Double.valueOf(count) * price.doubleValue();
        }
        //修改订单的发货总金额
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setOrderEndMoney(new BigDecimal(String.valueOf(moneyAll)).setScale(2, BigDecimal.ROUND_HALF_UP));

        if(relList.size() > 0)zsyhAgentOrderService.batchZsyhAgentOrderRel(relList);
        if(relListUpdate.size() > 0)zsyhAgentOrderService.batchUpdateZsyhAgentOrderRel(relListUpdate);
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);//保存订单信息 产品信息

        return success("操作成功");

    }

    /**
     * 删除订单的产品信息
     * @return
     */
    @RequestMapping("/deleteOrderPartsById")
    @ResponseBody
    @Transactional
    public AjaxResult deleteOrderPartsById(String id, String orderId){
        zsyhAgentOrderRelService.deleteZsyhAgentOrderRelById(id);
        return success("操作成功");
    }

    /**
     * 保存订单数据
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/saveOrderData")
    @ResponseBody
    @Transactional
    public AjaxResult saveOrderData(String id, String bankName, String bankUserName, String bankCardNo, String logistics, String logisticsNo, String partsJson){
        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhAgentOrderRel> relList = new ArrayList<>();
        //保存订单信息
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setBankName(bankName);
        order.setBankUserName(bankUserName);
        order.setBankCardNo(bankCardNo);
        order.setLogistics(logistics);
        order.setLogisticsNo(logisticsNo);

        Date date = new Date();
        double moneyAll = 0.00;
        for(Map<String, Object> a:list){//解析预定产品，并保存
            String relId = String.valueOf(a.get("id"));
            String count = String.valueOf(a.get("orderCount"));
            BigDecimal price = new BigDecimal(String.valueOf(a.get("orderPrice")));

            ZsyhAgentOrderRel rel = ZsyhAgentOrderRel.getInstance();
            rel.setId(relId);
            rel.setOrderSellCount(count);
            rel.setOrderSellPrice(price);
            rel.setCreateTime(date);

            relList.add(rel);

            moneyAll += Double.valueOf(count) * price.doubleValue();
        }
        order.setOrderEndMoney(new BigDecimal(String.valueOf(moneyAll)).setScale(2, BigDecimal.ROUND_HALF_UP));
        //order.setZsyhAgentOrderRelList(relList);
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);//保存订单信息 产品信息
        if(relList.size() > 0){
            zsyhAgentOrderRelService.updateZsyhAgentOrderRelBatch(relList);//批量修改产品信息 售价 发货数量
        }

        return success("操作成功");

    }

    /**
     * 生成发货单 确认发货
     * @return
     */
    @RequestMapping("/confirmDeliverOrder")
    @ResponseBody
    @Transactional
    public AjaxResult generateDeliverOrder(String id, String bankName, String bankUserName, String bankCardNo, String logistics, String logisticsNo,String logisticsImg, String partsJson){
        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhAgentOrderRel> relList = new ArrayList<>();
        //保存订单信息
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setOrderState("3");
        order.setBankName(bankName);
        order.setBankUserName(bankUserName);
        order.setBankCardNo(bankCardNo);
        order.setLogistics(logistics);
        order.setLogisticsNo(logisticsNo);
        order.setLogisticsImg(logisticsImg);

        Date date = new Date();
        double moneyAll = 0.00;
        String attributeIds = "";
        Map<String, String> map = new HashMap<>();
        for(Map<String, Object> a:list){//解析预定产品，并保存
            String relId = String.valueOf(a.get("id"));
            String attributeId = String.valueOf(a.get("attributeId"));
            String count = String.valueOf(a.get("orderCount"));
            BigDecimal price = new BigDecimal(String.valueOf(a.get("orderPrice")));

            ZsyhAgentOrderRel rel = ZsyhAgentOrderRel.getInstance();
            rel.setId(relId);
            rel.setOrderSellCount(count);
            //rel.setOrderPrice(price);
            rel.setOrderSellPrice(price);
            rel.setUpdateTime(date);

            relList.add(rel);

            moneyAll += Double.valueOf(count) * price.doubleValue();

            attributeIds += attributeId + ",";//拼接规格id
            if(map != null && map.size() > 0){
                String numStr = map.get(attributeId);
                if(EmptyUtils.isNotEmpty(numStr)){
                    count = String.valueOf(Double.valueOf(count) + Double.valueOf(numStr));
                }
            }
            map.put(attributeId, count);
            map.put(attributeId + "_price", price.toString());
        }
        order.setOrderEndMoney(new BigDecimal(String.valueOf(moneyAll)).setScale(2, BigDecimal.ROUND_HALF_UP));
        //order.setZsyhAgentOrderRelList(relList);
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);//保存订单信息 产品信息
        if(relList.size() > 0)zsyhAgentOrderRelService.updateZsyhAgentOrderRelBatch(relList);//批量修改产品信息 售价 发货数量


        String dateString = DateUtils.getDate();
        Integer year = Integer.valueOf(dateString.substring(0,4));
        Integer month = Integer.valueOf(dateString.substring(5,7));
        List<ZsyhPartsSales> salesList = zsyhPartsSalesService.getPartsSalesList(year, month, attributeIds);
        List<ZsyhPartsSales> saveSalesList = new ArrayList<>();
        List<ZsyhPartsSales> updateSalesList = new ArrayList<>();
        for(ZsyhPartsSales a:salesList){
            String salesId = a.getId();
            String factoryId = a.getFactoryId();
            String partsId = a.getPartsId();
            String attributeId = a.getAttributeId();
            ZsyhPartsSales sale = new ZsyhPartsSales();

            BigDecimal partsPrice = new BigDecimal(map.get(attributeId + "_price"));
            BigDecimal count = new BigDecimal(map.get(attributeId));


            if(salesId != null){
//                BigDecimal bookNum = a.getBookNum();
                BigDecimal deliveryNum = a.getDeliveryNum();
                BigDecimal deliveryMoney = a.getDeliveryMoney();
                deliveryNum = deliveryNum.add(count).setScale(2, BigDecimal.ROUND_HALF_UP);
                deliveryMoney = deliveryMoney.add(count.multiply(partsPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                sale.setId(salesId);
                sale.setDeliveryNum(deliveryNum);
                sale.setDeliveryMoney(deliveryMoney);
                updateSalesList.add(sale);
            }else{
                sale.setId(IdWorker.getId());
                sale.setFactoryId(factoryId);
                sale.setPartsId(partsId);
                sale.setBookNum(BigDecimal.ZERO);
                sale.setBookMoney(BigDecimal.ZERO);
                sale.setDeliveryNum(count.setScale(2, BigDecimal.ROUND_HALF_UP));
                sale.setDeliveryMoney(count.multiply(partsPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                sale.setAttributeId(attributeId);
                sale.setPeriodYear(year);
                sale.setPeriodMonth(month);
                saveSalesList.add(sale);
            }
        }
        if(saveSalesList.size() > 0)zsyhPartsSalesService.insertZsyhPartsSalesBatch(saveSalesList);
        if(updateSalesList.size() > 0)zsyhPartsSalesService.updateZsyhPartsSalesBatch(updateSalesList);

        //保存厂家消息
        order = zsyhAgentOrderService.selectZsyhAgentOrderById(id);
        String factoryName = order.getFactoryName();
        Date createTime = order.getCreateTime();
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
        String time = format.format(createTime).toString().substring(0, 10);
        ZsyhAgentMessage message = new ZsyhAgentMessage();
        message.setId(IdWorker.getId());
        message.setAgentId(order.getAgentId());
        message.setMessageContent("您于"+time+"预订的产品预订单，厂家"+factoryName+"已发货，请查看");
        message.setMessageStatus("0");
        zsyhAgentMessageService.insertZsyhAgentMessage(message);

        return success("操作成功");

    }

    /**
     * 上传发货凭证
     * @return
     */
    @RequestMapping("/uploadLogisticsImg")
    @ResponseBody
    @Transactional
    public AjaxResult uploadLogisticsImg(String id, String logisticsImg){

        //保存订单信息
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setLogisticsImg(logisticsImg);
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);//保存订单信息 产品信息


        return success("操作成功");

    }


    /**
     * 接单
     * @return
     */
    @RequestMapping("/generateDeliverOrder")
    @ResponseBody
    @Transactional
    public AjaxResult confirmDeliverOrder(String id){
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setOrderState("2");
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);//保存订单信息 产品信息
        return success("操作成功");

    }



    /**
     * 获取销售额
     * @return
     */
    @RequestMapping("/getFactorySalesVolume")
    @ResponseBody
    @Transactional
    public AjaxResult getFactorySalesVolume(String factoryId, String startDate, String endDate){
        if(EmptyUtils.isEmpty(startDate)){
            startDate = DateUtils.getMonthFirstDay();
        }
        if(EmptyUtils.isEmpty(endDate)){
            endDate = DateUtils.getDate();
        }
        startDate += " 00:00:00";
        endDate += " 23:59:59";

        List<Map> list = zsyhAgentOrderRelService.getFactorySalesVolume(startDate, endDate, factoryId);
        double moneyAll = 0.00;
        for(Map a:list){
            double money = Double.valueOf(String.valueOf(a.get("money")));
            moneyAll += money;
        }
        Map map = new HashMap();
        map.put("moneyAll", new BigDecimal(String.valueOf(moneyAll)).setScale(2, BigDecimal.ROUND_HALF_UP));
        map.put("startDate", startDate.substring(0, 10));
        map.put("endDate", endDate.substring(0, 10));
        map.put("list", list);
        return success("操作成功", map);

    }


    /**
     * 获取销售额 单个商品对应的管理商
     * @return
     */
    @RequestMapping("/getFactorySalesVolumeAgent")
    @ResponseBody
    public AjaxResult getFactorySalesVolumeAgent(String factoryId, String startDate, String endDate, String partsId){
        if(EmptyUtils.isEmpty(startDate)){
            startDate = DateUtils.getMonthFirstDay();
        }
        if(EmptyUtils.isEmpty(endDate)){
            endDate = DateUtils.getDate();
        }
        startDate += " 00:00:00";
        endDate += " 23:59:59";

        List<Map> list = zsyhAgentOrderRelService.getFactorySalesVolumeAgent(startDate, endDate, factoryId, partsId);

        Map map = new HashMap();
        map.put("partsId", partsId);
        map.put("startDate", startDate.substring(0, 10));
        map.put("endDate", endDate.substring(0, 10));
        map.put("list", list);
        return success("操作成功", map);

    }



    /**
     * 获取销售额 单个商品，单个管理商对应的订单详情
     * @return
     */
    @RequestMapping("/getFactorySalesVolumeOrderRel")
    @ResponseBody
    public AjaxResult getFactorySalesVolumeOrderRel(String factoryId, String startDate, String endDate, String partsId, String agentId){
        if(EmptyUtils.isEmpty(startDate)){
            startDate = DateUtils.getMonthFirstDay();
        }
        if(EmptyUtils.isEmpty(endDate)){
            endDate = DateUtils.getDate();
        }
        startDate += " 00:00:00";
        endDate += " 23:59:59";

        List<Map> list = zsyhAgentOrderRelService.getFactorySalesVolumeOrderRel(startDate, endDate, factoryId, partsId, agentId, "1");//获取订单数据
        List<Map> relList = zsyhAgentOrderRelService.getFactorySalesVolumeOrderRel(startDate, endDate, factoryId, partsId, agentId, "0");//获取订单产品数据
        for(Map a:list){
            String orderId = a.get("order_id").toString();
//            String create_time = a.get("create_time").toString();
            List<Map> _relList = new ArrayList<>();
            for(Map b:relList){
                String orderIdB = b.get("order_id").toString();
                if(orderId.equals(orderIdB)){
                    _relList.add(b);
                }
            }
            a.put("relList", _relList);
        }

//        Map map = new HashMap();
//        map.put("partsId", partsId);
//        map.put("agentId", agentId);
//        map.put("startDate", startDate.substring(0, 10));
//        map.put("endDate", endDate.substring(0, 10));
//        map.put("list", list);
        return success("操作成功", list);

    }


    /**
     * 获取合作产品
     * @return
     */
    @RequestMapping("/getFactoryPartsList")
    @ResponseBody
    public AjaxResult getFactoryPartsList(String factoryId){
        ZsyhPlatformParts parts = new ZsyhPlatformParts();
        parts.setFactoryId(factoryId);
        List<ZsyhPlatformParts> list = zsyhPlatformPartsService.selectZsyhPlatformPartsList(parts);
        return success("操作成功", list);

    }


    /**
     * 根据产品id获取全部型号
     * @return
     */
    @RequestMapping("/getFactoryPartsAttributeList")
    @ResponseBody
    public AjaxResult getFactoryPartsAttributeList(String factoryId, String partsId){
        ZsyhPlatformPartsattribute attribute = new ZsyhPlatformPartsattribute();
        attribute.setPartsId(partsId);
        List<ZsyhPlatformPartsattribute> list = zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeList(attribute);
        return success("操作成功", list);

    }

    /**
     * 获取产品详情
     * @return
     */
    @RequestMapping("/getFactoryPartsDetails")
    @ResponseBody
    public AjaxResult getFactoryPartsDetails(String partsId){
        return success("操作成功", zsyhPlatformPartsService.selectZsyhPlatformPartsById(partsId));
    }


    /**
     * 完善说明
     * @return
     */
    @RequestMapping("/updatePartsInstructions")
    @ResponseBody
    public AjaxResult updatePartsInstructions(String partsId, String partsDamageDetails, String partsAttention, String partsInstructions){
        ZsyhPlatformParts parts = new ZsyhPlatformParts();
        parts.setId(partsId);
        parts.setPartsDamageDetails(partsDamageDetails);
        parts.setPartsAttention(partsAttention);
        parts.setPartsInstructions(partsInstructions);
        zsyhPlatformPartsService.updateZsyhPlatformParts(parts);
        return success("操作成功");
    }

    /**
     * 获取平台客户列表
     * @return
     */
    @RequestMapping("/getPlatformUserList")
    @ResponseBody
    public AjaxResult getPlatformUserList(String factoryId){
        return success("操作成功", zsyhAgentOrderService.getPlatformUserList(factoryId));
    }


    /**
     * 获取平台客户发货记录
     * @return
     */
    @RequestMapping("/getPlatformUserOrderList")
    @ResponseBody
    @Transactional
    public AjaxResult getPlatformUserOrderList(String pageNum, String pageSize, String factoryId,String agentId){
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setFactoryId(factoryId);
        Map map = new HashMap();
        map.put("orderState", "3");
        int num = 0;
        int size = 10;
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            num = Integer.valueOf(pageNum);
            size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
        }
        map.put("beginPos", num);
        map.put("pageSize", size);
        order.setParams(map);
        order.setAgentId(agentId);
        List<ZsyhAgentOrder> list = zsyhAgentOrderService.selectZsyhAgentOrderList(order);
        return success("操作成功", list);

    }

    /**
     * 申请二维码标签
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/applyQrCodeFactoryId")
    @ResponseBody
    @Transactional
    public AjaxResult applyQrCodeFactoryId(String factoryId, String attributeId, long num) throws Exception{
        Map map = zsyhAgentOrderRelService.getAgentOrderRelOrderCount(attributeId);
        double orderNum = Double.valueOf(map.get("num").toString());
        if(orderNum < num){
            return error("申请二维码的数量不能大于待发货订单数量");
        }
        ZsyhPlatformFactory factory = zsyhPlatformFactoryService.selectZsyhPlatformFactoryById(factoryId);

        ZsyhPlatformPartsattribute attribute = zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeById(attributeId);
        BigDecimal payPrice = attribute.getAttributePayPrice();
        logger.info("attribute-------------------" + attribute);
        logger.info("payPrice-------------------" + payPrice);
        String install = attribute.getAttributeInstall();
        if(EmptyUtils.isEmpty(install)){
            install = "0";
        }
        String qRCodeFirst = System.currentTimeMillis() + StringUtils.getRandomCode();
        String qRCode = qRCodeFirst + "00000000001";
        Date date = new Date();

        ZsyhPartsQrcode partsQrcode = new ZsyhPartsQrcode();
        partsQrcode.setQrcodeId(qRCode);
        partsQrcode.setPartsId(attribute.getPartsId());
        partsQrcode.setAttributeId(attributeId);
        partsQrcode.setProductionDate(date);
        partsQrcode.setDeadlineDate(DateUtils.addMonths(date,Integer.parseInt(install)));
        partsQrcode.setPayPrice(payPrice);
        partsQrcode.setCreateTime(date);
        partsQrcode.setQrcodeSort(num);
        zsyhPartsQrcodeService.insertZsyhPartsQrcode(partsQrcode);

        ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory = new ZsyhPartsQrcodeHistory();
        zsyhPartsQrcodeHistory.setId(IdWorker.getId());
        zsyhPartsQrcodeHistory.setPartsId(attribute.getPartsId());
        zsyhPartsQrcodeHistory.setAttributeId(attributeId);
        zsyhPartsQrcodeHistory.setStartCode(1L);
        zsyhPartsQrcodeHistory.setEndCode(num);
        zsyhPartsQrcodeHistory.setApplyNum(num);
        zsyhPartsQrcodeHistory.setQrcodeFirst(qRCodeFirst);
        zsyhPartsQrcodeHistory.setPayPrice(payPrice);
        zsyhPartsQrcodeHistory.setCreateTime(date);
        zsyhPartsQrcodeHistory.setOperateName(factory.getFactoryPerson());
        zsyhPartsQrcodeHistoryService.insertZsyhPartsQrcodeHistory(zsyhPartsQrcodeHistory);

        String QrcodeFirst = qRCode.substring(0,15);
        Long qRCodeAfter = Long.valueOf(qRCode.substring(15,qRCode.length()));
        Long codeNum = Long.valueOf(qRCode.substring(16,19) + qRCode.substring(25,30));

        // 每次写100行数据，就刷新数据出缓存
        XSSFWorkbook wb = new XSSFWorkbook(); // keep 100 rows in memory,
        Sheet sh = wb.createSheet();
        // 这个是业务数据
        String[] titles = {"序号", "二维码编码", "编码值", "生成时间", "产品编码", "产品名称", "配件型号", "损坏赔付金额"};
        Row row = sh.createRow(0);
        // 第一行设置标题
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
        }
        // 导出数据
        for (int rowNum = 0; rowNum < num; rowNum++) {

            Row rowData = sh.createRow(rowNum + 1);
            // TbClass 这个是我的业务类，这个是根据业务来进行填写数据
            // 第一列
            Cell cellDataA = rowData.createCell(0);
            cellDataA.setCellValue(rowNum + 1);
            // 第二列
            Cell cellDataB = rowData.createCell(1);

            if(rowNum > 0){
                qRCodeAfter ++;
                codeNum ++;
            }
            qRCode = QrcodeFirst + qRCodeAfter;
            cellDataB.setCellValue("https://xcx.zzzsyh.com/index.html?qrcode=" + qRCode);
            // 第三列
            Cell cellDataC = rowData.createCell(2);
            cellDataC.setCellValue(String.valueOf(codeNum));

            // 第四列
            Cell cellDataD = rowData.createCell(3);
            cellDataD.setCellValue(DateUtils.getDate());

            // 第五列
            Cell cellDataE = rowData.createCell(4);
            cellDataE.setCellValue(attribute.getPartsNumber());
            // 第六列
            Cell cellDataF = rowData.createCell(5);
            cellDataF.setCellValue(attribute.getPartsName());
            // 第七列
            Cell cellDataG = rowData.createCell(6);
            cellDataG.setCellValue(attribute.getAttributeName());
            // 第八列
            if(EmptyUtils.isNotEmpty(payPrice)){
                Cell cellDataL = rowData.createCell(7);
                cellDataL.setCellValue(String.valueOf(payPrice));
            }else{
                Cell cellDataL = rowData.createCell(7);
                cellDataL.setCellValue(0);
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        wb.close();
//        EmailUtil.sendMail("主事丫环二维码表格","64295651@qq.com","您好，附件是二维码表，请查收",new ByteArrayInputStream(os.toByteArray()));
        boolean fl = EmailUtil.sendMail("主事丫环二维码表格",factory.getFactoryEmail(),"您好，附件是二维码表，请查收",new ByteArrayInputStream(os.toByteArray()));
        return success("操作成功", fl);

    }

    /**
     * 获取二维码申请记录列表
     * @return
     */
    @RequestMapping("/getQrCodeHistoryList")
    @ResponseBody
    public AjaxResult getQrCodeHistoryList(String attributeId){
        ZsyhPartsQrcodeHistory history = new ZsyhPartsQrcodeHistory();
        history.setAttributeId(attributeId);
        return success("操作成功", zsyhPartsQrcodeHistoryService.selectZsyhPartsQrcodeHistoryList(history));
    }



}
